package common;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;

public class FileDownloader {
    public static boolean downloadFile(String fileUrl, String savePath) {
        System.out.printf("文件下载中（HttpURLConnection）：%s",fileUrl);
        try {
            // 创建URL对象
            URL url = URI.create(fileUrl).toURL();
            // 创建连接对象
            HttpURLConnection conn;
            if (fileUrl.toLowerCase().startsWith("https://")) {
                conn= (HttpsURLConnection) url.openConnection();
            }else conn= (HttpURLConnection) url.openConnection();
            // 设置请求方法为GET
            conn.setRequestMethod("GET");
            // 获取输入流
            InputStream inputStream = conn.getInputStream();
            System.out.printf("文件大小：%s\n",conn.getContentLengthLong());
            // 创建输出流
            OutputStream outputStream = new FileOutputStream(savePath);
            // 缓冲区
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 循环写入文件
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                outputStream.flush();
            }
            // 关闭流
            outputStream.close();
            inputStream.close();
            File thatFile=new File(savePath);
            if (!thatFile.exists()||thatFile.length()==0){
                System.err.println("文件下载失败：文件大小0kb，已删除下载的文件");
                thatFile.deleteOnExit();
                return false;
            }
            System.out.printf("文件下载成功，文件路径：%s\n",savePath);
        } catch (IOException e) {
            System.out.printf("文件下载失败：%s\n",e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
